import 'package:flutter/material.dart';

class MySliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  final Function(int) updateIndexSelect;
  final ValueNotifier<int> _indexSelectNotifier;

  MySliverPersistentHeaderDelegate(int indexSelect, this.updateIndexSelect)
      : _indexSelectNotifier = ValueNotifier<int>(indexSelect);

  final tabArr = ['发布', '收藏', '喜欢'];

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return ValueListenableBuilder<int>(
      valueListenable: _indexSelectNotifier,
      builder: (context, indexSelect, child) {
        return Container(
          color: Colors.white,
          height: 40,
          child: Row(
            children: [
              for (int i = 0; i < tabArr.length; i++)
                GestureDetector(
                  onTap: () {
                    _indexSelectNotifier.value = i;
                    updateIndexSelect(i);
                  },
                  child: Container(
                      margin: const EdgeInsets.all(0),
                      height: 28,
                      width: 70,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(tabArr[i],
                              style: TextStyle(
                                  fontSize: i == indexSelect ? 17 : 15,
                                  color: i == indexSelect
                                      ? Colors.black
                                      : Colors.grey)),
                          Visibility(
                            visible: i == indexSelect,
                            child: Container(
                              height: 1,
                              width: 40,
                              color: Colors.black,
                            ),
                          )
                        ],
                      )),
                ),
            ],
          ),
        );
      },
    );
  }

  @override
  double get maxExtent => 40; // 与 build 方法中的 Container 高度一致

  @override
  double get minExtent => 40;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    // 只有当 indexSelect 改变时才进行重建
    return true;
  }
}